package org.dsc.amafinder.dialog;

import org.dsc.amafinder.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class CloseAppDialogFragment extends DialogFragment {
   private static final String TAG = "afr." + CloseAppDialogFragment.class.getSimpleName();
   
   private static CloseAppDialogFragment me = null;
   private static Activity mParent = null;
   
   public static CloseAppDialogFragment newInstance(final Activity parentActivity) {
      if (null == me || parentActivity != mParent) { 
         mParent = parentActivity;
         me = new CloseAppDialogFragment();
         
//         me.setStyle(STYLE_NO_TITLE, R.style.Theme_Dialog_Translucent);
//         me.setCancelable(false);
      }
      return me;
   }

   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
      android.app.AlertDialog.Builder dlgBuilder = new AlertDialog.Builder(getActivity());
      dlgBuilder.setMessage(getResources().getString(R.string.salir_amafinder_seguro));
      // inflater dlgBuilder.setView(view)
      dlgBuilder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            dismiss();
            Toast.makeText(mParent, R.string.buena_eleccion, Toast.LENGTH_SHORT).show();
         }
      });
      dlgBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
         public void onClick(final DialogInterface dialog, int id) {
            dismiss();
            Toast.makeText(mParent, R.string.hasta_pronto, Toast.LENGTH_SHORT).show();
            continueShutdown();            
         }
      });
      return dlgBuilder.create();
   }

   protected void continueShutdown() {
      ProgressDialogFragment mDialog = ProgressDialogFragment.newInstance();
      mDialog.show(getFragmentManager(), "Shutdown");
      finishShutdown();
   }

   private void finishShutdown() {
      new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               // Pretend to do something before
               // shutting down
               Thread.sleep(5000);
            } catch (InterruptedException e) {
               Log.i(TAG, e.toString());
            } finally {
               mParent.finish();
               Intent salida = new Intent();
               salida.setAction(Intent.ACTION_MAIN);
               salida.addCategory(Intent.CATEGORY_HOME);
               salida.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               mParent.startActivity(salida);
               android.os.Process.killProcess(android.os.Process.myPid());
            }
         }
      }).start();
   }
}

